package cn.pli.bike.ui;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.bigkoo.alertview.OnItemClickListener;
import com.framemodule.BaseApp.AppManager;
import com.framemodule.base.BaseActivityPresenter;
import com.framemodule.base.netstatus.NetUtils;
import com.framemodule.utils.CommonUtils;
import com.framemodule.utils.Logger;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.beacon.Beacon;
import com.inuker.bluetooth.library.connect.listener.BluetoothStateListener;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.inuker.bluetooth.library.utils.BluetoothLog;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.pli.bike.App;
import cn.pli.bike.Permission;
import cn.pli.bike.R;
import cn.pli.bike.base.BaseDialog;
import cn.pli.bike.bean.CheckUpdateBean;
import cn.pli.bike.bean.DepositBean;
import cn.pli.bike.bean.ExpensesRecordBean;
import cn.pli.bike.bean.HttpResult;
import cn.pli.bike.bean.LockBean;
import cn.pli.bike.bean.NoticeBean;
import cn.pli.bike.bean.OpenLockBean;
import cn.pli.bike.bean.OpenOrderBean;
import cn.pli.bike.bean.UserBean;
import cn.pli.bike.lib.LocationTask;
import cn.pli.bike.lib.PositionEntity;
import cn.pli.bike.lib.RegeocodeTask;
import cn.pli.bike.lib.RouteTask;
import cn.pli.bike.lib.Utils;
import cn.pli.bike.model.UserModel;
import cn.pli.bike.model.http.ApiException;
import cn.pli.bike.model.subscribers.ProgramSubscriber;
import cn.pli.bike.overlay.WalkRouteOverlay;
import cn.pli.bike.service.ConnectService;
import cn.pli.bike.utils.AMapUtil;
import cn.pli.bike.utils.AppUtils;
import cn.pli.bike.utils.ControlBlueUtils;
import cn.pli.bike.utils.DialogUtils;
import cn.pli.bike.utils.EventBusAction;
import cn.pli.bike.utils.ToastUtil;


import cn.pli.bike.lib.OnLocationGetListener;
import pub.devrel.easypermissions.EasyPermissions;
import twitter4j.User;


public class MainActivity extends BaseActivityPresenter<MainDelegate> implements
        AMap.OnMapLoadedListener, OnLocationGetListener, View.OnClickListener, RouteTask.OnRouteCalculateListener,
        AMap.OnMapTouchListener, RouteSearch.OnRouteSearchListener, AMap.OnMapClickListener, AMap.InfoWindowAdapter, AMap.OnCameraChangeListener, DialogInterface.OnDismissListener {


    private int userType = USER_LOGON;
    public static final int USER_LOGON = 0;            //用户没有登录
    public static final int USER_NO_DEPOSIT = 1;        //用户没有交押金
    public static final int USER_CAN_RIDE = 2;          //用户已经交
    public static final int USER_NO_BALANCE = 3;          //账户余额不足
    public static final int USER_NO_REAL_NAME_AUTH = 4;
    private UserBean userBean;//用户数据
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            // Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS
    };

    String[] locPermissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    String type;

    CheckUpdateBean checkUpdateBean;
    private LockBean lockBean;
    protected Dialog loadingDialog;

    private boolean isOpen = false;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;
    private final int PERMISSON_REQUESTCODE = 0;


    public static final String TAG = "MainActivity";
    public static final int REQUEST_CODE = 1;
    MapView mMapView = null; //地图view
    AMap aMap; //初始化地图控制器对象
    private LocationTask mLocationTask; //定位
    private RegeocodeTask mRegeocodeTask;//逆地理编码功能
    private Marker mPositionMark, mInitialMark, tempMark;//可移动、圆点、点击 //绘制点标记
    private LatLng mStartPosition, mRecordPositon;//初始坐标、移动记录坐标
    private boolean mIsFirst = true;//默认添加一次
    private boolean mIsFirstShow = true;//就第一次显示位置
    private LatLng initLocation;
    private ValueAnimator animator = null;//坐标动画
    private BitmapDescriptor initBitmap, moveBitmap, smallIdentificationBitmap, bigIdentificationBitmap;//定位圆点、可移动、所有标识（车）
    private RouteSearch mRouteSearch;
    private WalkRouteResult mWalkRouteResult;
    private LatLonPoint mStartPoint = null;//起点，116.335891,39.942295
    private LatLonPoint mEndPoint = null;//终点，116.481288,39.995576
    private final int ROUTE_TYPE_WALK = 3;
    private boolean isClickIdentification = false;
    WalkRouteOverlay walkRouteOverlay;//路线
    private String[] time;
    private String distance;
    boolean isRiding;
    OpenOrderBean openOrderBean;

    private Timer timer;
    private OpenLockBean openLockBean;
    private MediaPlayer mediaPlayer;
    //蓝牙
    protected BluetoothClient mBtClient;
    private List<BluetoothDevice> mBtItems = new ArrayList<>();
    private BluetoothStateListener btStateListener;
    private boolean isScanning = true;
    private String blueMac;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mMapView = findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initBitmap();
        initAMap();
        initLocation();
        RouteTask.getInstance(getApplicationContext())
                .addRouteCalculateListener(this);
        EventBus.getDefault().register(this);
        if (getIntent().hasExtra("type")) {
            type = getIntent().getStringExtra("type");
            userBean = (UserBean) getIntent().getSerializableExtra("userBean");
        }
        checkVersion();

        mBtClient = new BluetoothClient(this);
        initBT();
    }

    /**
     * 检查更新
     */
    private void checkVersion() {
        if (this.checkUpdateBean != null && this.checkUpdateBean.getVersionCode() >= cn.pli.bike.base.CommonConstant.checkUpdateBean.getVersionCode()) {
            return;
        }

        this.checkUpdateBean = cn.pli.bike.base.CommonConstant.checkUpdateBean;
        if (checkUpdateBean != null) {
            if (CommonUtils.getVersionCode(this) == -1) {
                return;
            }
            if (checkUpdateBean.getVersionCode() > CommonUtils.getVersionCode(this)) {
                showVersionDialog(checkUpdateBean);
            }
        }
    }

    /**
     *
     */
    private void showVersionDialog(final CheckUpdateBean checkUpdateBean) {
        final Dialog versionDialog = new BaseDialog(this, R.style.BaseDialog, R.layout.dialog_update_version);
        TextView tvUpdateInfo = versionDialog.findViewById(R.id.tv_update_version_info);
        TextView tvCancel = versionDialog.findViewById(R.id.tv_cancel);
        TextView tvUpdate = versionDialog.findViewById(R.id.tv_update);
        //设置dismiss listener 用于强制更新,dimiss会回调dialogDismiss方法
        versionDialog.setOnDismissListener(this);
        tvUpdateInfo.setText(checkUpdateBean.getDescription());
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                versionDialog.dismiss();
                if (CheckUpdateBean.FORCE_UPDATE.equals(checkUpdateBean.getToUpdate())) {
                    AppManager.getAppManager().finishAllActivity();
                }
            }
        });
        tvUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, ConnectService.class);
                intent.setType(ConnectService.TYPE_DOWN_LOAD_APK);
                intent.putExtra("url", checkUpdateBean.getDownloadPath());
                startService(intent);
                versionDialog.dismiss();
            }
        });


        versionDialog.show();
    }


    private void initBitmap() {
        initBitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.location_marker);
        moveBitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_loaction_start);
        smallIdentificationBitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.stable_cluster_marker_one_normal1);
        bigIdentificationBitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.stable_cluster_marker_one_normal1);
    }

    /**
     * 初始化地图控制器对象
     */
    private void initAMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
            mRouteSearch = new RouteSearch(this);
            mRouteSearch.setRouteSearchListener(this);
            aMap.getUiSettings().setZoomControlsEnabled(false);
            aMap.getUiSettings().setGestureScaleByMapCenter(true);
//            aMap.getUiSettings().setScrollGesturesEnabled(false);
            aMap.setOnMapTouchListener(this);
            aMap.setOnMapLoadedListener(this);
            aMap.setOnCameraChangeListener(this);
            aMap.setOnMapClickListener(this);
            // 绑定 Marker 被点击事件
            aMap.setOnMarkerClickListener(markerClickListener);
            aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        }
    }

    /**
     * 初始化定位
     */
    private void initLocation() {
        mLocationTask = LocationTask.getInstance(getApplicationContext());
        mLocationTask.setOnLocationGetListener(this);
        mRegeocodeTask = new RegeocodeTask(getApplicationContext());
    }

    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {

        // marker 对象被点击时回调的接口
        // 返回 true 则表示接口已响应事件，否则返回false
        @Override
        public boolean onMarkerClick(final Marker marker) {
            Log.e(TAG, "点击的Marker");
            Log.e(TAG, marker.getPosition() + "");
            isClickIdentification = true;
            if (tempMark != null) {
                tempMark.setIcon(smallIdentificationBitmap);
                walkRouteOverlay.removeFromMap();
                tempMark = null;
            }
            startAnim(marker);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(300);
                        tempMark = marker;
                        mStartPoint = new LatLonPoint(mRecordPositon.latitude, mRecordPositon.longitude);
                        mPositionMark.setPosition(mRecordPositon);
                        mEndPoint = new LatLonPoint(marker.getPosition().latitude, marker.getPosition().longitude);
                        marker.setIcon(bigIdentificationBitmap);
                        marker.setPosition(marker.getPosition());
                        searchRouteResult(ROUTE_TYPE_WALK, RouteSearch.WalkDefault);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            return true;
        }
    };

    private void startAnim(Marker marker) {
        ScaleAnimation anim = new ScaleAnimation(1.0f, 1.3f, 1.0f, 1.3f);
        anim.setDuration(300);
        marker.setAnimation(anim);
        marker.startAnimation();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                checkPermissions(needPermissions);
            }
        }


        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
        if (mInitialMark != null) {
            mInitialMark.setToTop();
        }
        if (mPositionMark != null) {
            mPositionMark.setToTop();
        }

        token = App.getShareSetting().loadString("token");
        if (CommonUtils.isEmpty(token)) {
            setUserType(USER_LOGON);
        } else {
            getUserInfo();
            JPushInterface.setAlias(this, AppUtils.getUserId(), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    Logger.d(s);
                }
            });
        }

        if (CommonUtils.isEmpty(AppUtils.getComPhone())) {
            getDeposit();
        }

        getOrder();


    }

    private void getOrder() {
        isRiding = false;
        long startTime = System.currentTimeMillis();
        if (openOrderBean != null) {
            startTime = openOrderBean.getBeginTime();
        }
        long interval = System.currentTimeMillis() - startTime;
        if (interval < 5 * 1000) {
            // return;
        }

        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        viewDelegate.getRlRiding().setVisibility(View.GONE);
        viewDelegate.get(R.id.iv_main_scan_open).setVisibility(View.VISIBLE);
        UserModel.selectOpenOrder(new ProgramSubscriber<HttpResult<OpenOrderBean>>() {
            @Override
            public void onNext(HttpResult<OpenOrderBean> openOrderBeanHttpResult) {
                if (openOrderBeanHttpResult.getData() != null) {
                    openOrderBean = openOrderBeanHttpResult.getData();
                    showRidingState();
                }
            }

        });
    }

    private void showRidingState() {
        isRiding = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = EventBusAction.UPDATE_RIDING_TIME;
                EventBus.getDefault().post(message);
            }
        }, 1000, 1000);
        viewDelegate.get(R.id.iv_main_scan_open).setVisibility(View.GONE);
        viewDelegate.getRlRiding().setVisibility(View.VISIBLE);
        viewDelegate.getTvStartTime().setText(getString(R.string.open_lock_time) + CommonUtils.formatLong(openOrderBean.getBeginTime()));
        viewDelegate.getTvRidingBikeNumber().setText(getString(R.string.riding_bike_number) + AppUtils.getLockNumber());
    }

    @Override
    protected void initModel() {

    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.setOnClickListener(this, R.id.iv_title_menu, R.id.iv_title_search, R.id.tv_main_user_state_action, R.id.iv_main_location,
                R.id.iv_main_scan_open, R.id.iv_main_service, R.id.iv_title_gift, R.id.bt_confirm);
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    public void onClick(View v) {
        if (!AppUtils.isLogin()) {
            readyGo(PhoneLogonActivity.class);
            AppManager.getAppManager().finishAllActivity();
            return;
        }

        switch (v.getId()) {
            //个人中心
            case R.id.iv_title_menu:
                readyGo(UserInfoActivity.class);
                break;
            //搜索地点
            case R.id.iv_title_search:
                readyGo(DestinationActivity.class);
                break;
            //登录或交押金
            case R.id.tv_main_user_state_action:
                switch (userType) {
                    //登录
                    case USER_LOGON:
                        logon();
                        break;
                    //充押金
                    case USER_NO_DEPOSIT:
                        paymentDeposit();
                        break;
                    case USER_NO_REAL_NAME_AUTH:
                        readyGo(UserAuthActivity.class);
                        break;
                }
                break;
            //定位
            case R.id.iv_main_location:
                clickRefresh();
                //initLoc();
                break;
            //扫描开锁
            case R.id.iv_main_scan_open:
                if (userBean == null) {
                    return;
                }
                if (!(userBean.getDeposit() > 0)) {
                    viewDelegate.toast(getResources().getString(R.string.user_no_deposit));
                    return;
                }
                if (!AppUtils.isAuthStatus()) {
                    viewDelegate.toast(getResources().getString(R.string.user_no_realname_auth));
                    return;
                }
                if (!(userBean.getAvailableAmount() > 0)) {
                    viewDelegate.toast(getResources().getString(R.string.no_balance_can_not_ride));
                    readyGo(YourWalletActivity.class);
                    return;
                }

                isScanning = true;
                mBtItems.clear();
                if (!mBtClient.isBluetoothOpened()) {
                    mBtClient.openBluetooth();
                } else {
                    scanBt();//扫描蓝牙
                }


                viewDelegate.showAlert1("T-bike单车仅在景区有限范围内骑行，请勿骑出景区", "确定", new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });

                break;
            //客服帮助
            case R.id.iv_main_service:
                showDialog();
                break;
            case R.id.iv_title_gift:
                readyGo(GiftActivity.class);
                break;
            case R.id.bt_confirm:
                viewDelegate.getRlRideEnd().setVisibility(View.GONE);
                break;
        }

    }

    private void logon() {
        readyGo(PhoneLogonActivity.class);
    }

    /**
     * 缴纳押金
     */
    private void paymentDeposit() {
        readyGo(PaymentDepositActivity.class);

    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
       /* if ("PhoneLogonActivity".equals(type)) {
            type = "";
            return;
        }*/
        UserModel.postloginByToken(new ProgramSubscriber<HttpResult<UserBean>>() {
            @Override
            public void onNext(HttpResult<UserBean> userBeanHttpResult) {
                JPushInterface.setAlias(getApplicationContext(),
                        userBeanHttpResult.getData().getId(),
                        null);
                userBean = userBeanHttpResult.getData();
                AppUtils.saveUserInfo(userBeanHttpResult.getData());
                if (!(userBean.getDeposit() > 0)) {
                    setUserType(USER_NO_DEPOSIT);
                    return;
                }
                if (!AppUtils.isAuthStatus()) {
                    setUserType(USER_NO_REAL_NAME_AUTH);
                    return;
                }
                setUserType(USER_CAN_RIDE);


            }
        });
    }

    /**
     * 获取押金电话等
     */
    private void getDeposit() {
        UserModel.getDeposit(new ProgramSubscriber<HttpResult<DepositBean>>() {
            @Override
            public void onNext(HttpResult<DepositBean> userBeanHttpResult) {
                AppUtils.saveDeposit(userBeanHttpResult.getData());
            }
        });
    }

    /**
     * 设置用户类型
     *
     * @param type
     */
    private void setUserType(int type) {
        userType = type;
        viewDelegate.setUserState(userType);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                String qrresult = bundle.getString(CodeUtils.RESULT_STRING);
                String lockNum = "";
                if (CommonUtils.isEmpty(qrresult)) {
                    viewDelegate.toast(getString(R.string.scan_qr_error));
                    return;
                }
                if (qrresult.contains("=")) {
                    String[] results = qrresult.split("=");
                    lockNum = results[results.length - 1];
                } else {
                    lockNum = qrresult;
                }


                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    final String finalLockNum = lockNum;
                    AppUtils.saveLockNumber(finalLockNum);
                    checkLockInfo(lockNum);

                    // open2GLock(lockNum);


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, R.string.can_not_get_qrcode, Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    /**
     * 打开2G锁
     *
     * @param lockNum
     */
    private void open2GLock(String lockNum) {
        UserModel.openLockScan(new ProgramSubscriber<HttpResult<OpenLockBean>>() {
            @Override
            public void onNext(HttpResult<OpenLockBean> httpResult) {
                //Logger.d(stringHttpResult.getMsg());
                openLockBean = httpResult.getData();
                readyGo(OpenLockActivity.class);
            }

            @Override
            public void onErr(ApiException e) {
                super.onErr(e);
                viewDelegate.toast(e.getMsg());
            }
        }, lockNum, App.getApp().amapLocation.getLongitude() + "", App.getApp().amapLocation.getLatitude() + "");
    }


    private void checkLockInfo(final String lockNum) {
        UserModel.getLockByLocknum(new ProgramSubscriber<HttpResult<LockBean>>() {
            @Override
            public void onNext(HttpResult<LockBean> lockBeanHttpResult) {
                isOpen = false;
                lockBean = lockBeanHttpResult.getData();
                connectAndOpen(lockBeanHttpResult.getData());
                if (lockBeanHttpResult.getData().getBikeType().equals(LockBean.LOCK_BLUE)) {
                    connectAndOpen(lockBeanHttpResult.getData());
                } else {
                    open2GLock(lockNum);
                }


            }

            @Override
            public void onErr(ApiException e) {
                super.onErr(e);
                viewDelegate.toast(e.getMsg());
            }
        }, lockNum);
    }


    /**
     * 举报
     */
    private void showDialog() {
        final Dialog dialog = DialogUtils.getDownToUpDialog(this, R.layout.alert_dialog_call_center);
        LinearLayout llIllegalParking, llFault, llCallCenter;
        llIllegalParking = dialog.findViewById(R.id.ll_report_illegal_parking);
        llFault = dialog.findViewById(R.id.ll_report_fault);
        llCallCenter = dialog.findViewById(R.id.ll_call_center);
        llIllegalParking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                String title = getString(R.string.report_illegal_parking);
                int type = CallCenterActivity.REPORT_ILLDAGAL;
                bundle.putInt("type", type);
                bundle.putString("title", title);
                readyGo(ProblemDetailActivity.class, bundle);
                dialog.dismiss();

            }
        });
        llFault.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                String title = getString(R.string.report_fault);
                int type = CallCenterActivity.REPORT_FAULT;
                bundle.putInt("type", type);
                bundle.putString("title", title);
                readyGo(ProblemDetailActivity.class, bundle);
                dialog.dismiss();

            }
        });
        llCallCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readyGo(CallCenterActivity.class);
                dialog.dismiss();

            }
        });


        dialog.show();
    }

    @Override
    protected void onDestroy() {
        if (mBtClient != null) {
            if (btStateListener != null)
                mBtClient.unregisterBluetoothStateListener(btStateListener);
            mBtClient.stopSearch();
        }
        super.onDestroy();
        Utils.removeMarkers();
        mMapView.onDestroy();
        mLocationTask.onDestroy();
        RouteTask.getInstance(getApplicationContext()).removeRouteCalculateListener(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        mBtClient.stopSearch();
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }


    /**
     * @param
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class, int.class});

                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                }
            }
        } catch (Throwable e) {
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer) checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean) shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(grantResults)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }


    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("");
        builder.setMessage("");
        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancle,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });
        builder.setCancelable(false);
        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

        if (!isClickIdentification) {
            mRecordPositon = cameraPosition.target;
        }
        mStartPosition = cameraPosition.target;
        mRegeocodeTask.setOnLocationGetListener(this);
        mRegeocodeTask.search(mStartPosition.latitude, mStartPosition.longitude);
        Utils.addEmulateData(aMap, mStartPosition);
        if (mIsFirst) {
            createInitialPosition(cameraPosition.target.latitude, cameraPosition.target.longitude);
            createMovingPosition();
            mIsFirst = false;
        }
        if (mInitialMark != null) {
            mInitialMark.setToTop();
        }
        if (mPositionMark != null) {
            mPositionMark.setToTop();
            if (!isClickIdentification) {
                animMarker();
            }
        }
    }


    /**
     * 地图加载完成
     */
    @Override
    public void onMapLoaded() {
        mLocationTask.startLocate();
    }

    /**
     * 创建初始位置图标
     */
    private void createInitialPosition(double lat, double lng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.anchor(0.5f, 0.5f);
        markerOptions.position(new LatLng(lat, lng));
        markerOptions.icon(initBitmap);
        mInitialMark = aMap.addMarker(markerOptions);
        mInitialMark.setClickable(false);
    }

    /**
     * 创建移动位置图标
     */
    private void createMovingPosition() {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(new LatLng(0, 0));
        markerOptions.icon(moveBitmap);
        mPositionMark = aMap.addMarker(markerOptions);
        mPositionMark.setPositionByPixels(mMapView.getWidth() / 2,
                mMapView.getHeight() / 2);
        mPositionMark.setClickable(false);
    }


    @Override
    public void onRouteCalculate(float cost, float distance, int duration) {
        Log.e(TAG, "cost" + cost + "---" + "distance" + distance + "---" + "duration" + duration);
        PositionEntity endPoint = RouteTask.getInstance(getApplicationContext()).getEndPoint();
        mRecordPositon = new LatLng(endPoint.latitue, endPoint.longitude);
        clickMap();
        RouteTask.getInstance(getApplicationContext()).setEndPoint(null);
    }

    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (motionEvent.getPointerCount() >= 2) {
            aMap.getUiSettings().setScrollGesturesEnabled(false);
        } else {
            aMap.getUiSettings().setScrollGesturesEnabled(true);
        }
    }

    private void animMarker() {
        if (animator != null) {
            animator.start();
            return;
        }
        animator = ValueAnimator.ofFloat(mMapView.getHeight() / 2, mMapView.getHeight() / 2 - 30);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(150);
        animator.setRepeatCount(1);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (Float) animation.getAnimatedValue();
                mPositionMark.setPositionByPixels(mMapView.getWidth() / 2, Math.round(value));
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mPositionMark.setIcon(moveBitmap);
            }
        });
        animator.start();
    }

    private void endAnim() {
        if (animator != null && animator.isRunning())
            animator.end();
    }


    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {

    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult result, int errorCode) {
        // LoadDialog.getInstance().dismiss();
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getPaths() != null) {
                if (result.getPaths().size() > 0) {
                    mWalkRouteResult = result;
                    final WalkPath walkPath = mWalkRouteResult.getPaths()
                            .get(0);
                    walkRouteOverlay = new WalkRouteOverlay(
                            this, aMap, walkPath,
                            mWalkRouteResult.getStartPos(),
                            mWalkRouteResult.getTargetPos());
                    walkRouteOverlay.removeFromMap();
                    walkRouteOverlay.addToMap();
                    walkRouteOverlay.zoomToSpan();
                    int dis = (int) walkPath.getDistance();
                    int dur = (int) walkPath.getDuration();
                    time = AMapUtil.getFriendlyTimeArray(dur);
                    distance = AMapUtil.getFriendlyLength(dis);
                    String des = AMapUtil.getFriendlyTime(dur) + "(" + AMapUtil.getFriendlyLength(dis) + ")";
                    tempMark.setTitle(des);
                    tempMark.showInfoWindow();
                    Log.e(TAG, des);
                } else if (result != null && result.getPaths() == null) {
                }
            } else {
            }
        } else {
        }
    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    /**
     * 开始搜索路径规划方案
     */
    public void searchRouteResult(int routeType, int mode) {
        if (mStartPoint == null) {
            ToastUtil.show(this, getString(R.string.location_loading));
            return;
        }
        if (mEndPoint == null) {
            ToastUtil.show(this, getString(R.string.target_not_set));
        }
        // showDialog();
        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        if (routeType == ROUTE_TYPE_WALK) {// 步行路径规划
            RouteSearch.WalkRouteQuery query = new RouteSearch.WalkRouteQuery(fromAndTo, mode);
            mRouteSearch.calculateWalkRouteAsyn(query);// 异步路径规划步行模式查询
        }
    }

    /*  private void showDialog() {
          LoadDialog loadDialog = LoadDialog.getInstance();
          loadDialog.setStyle(DialogFragment.STYLE_NORMAL, R.style.load_dialog);
          LoadDialog.getInstance().show(getSupportFragmentManager(), "");
      }
  */
    @Override
    public void onMapClick(LatLng latLng) {
        clickMap();
    }

    private void clickRefresh() {
        clickInitInfo();
        if (initLocation != null) {
            CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                    initLocation, 17f);
            aMap.animateCamera(cameraUpate);
        }
    }

    private void clickMap() {
        clickInitInfo();
        if (mRecordPositon != null) {
            CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                    mRecordPositon, 17f);
            aMap.animateCamera(cameraUpate);
        }
    }

    private void clickInitInfo() {
        isClickIdentification = false;
        if (null != tempMark) {
            tempMark.setIcon(smallIdentificationBitmap);
            tempMark.hideInfoWindow();
            tempMark = null;
        }
        if (null != walkRouteOverlay) {
            walkRouteOverlay.removeFromMap();
        }
    }
/*

    @Override
    public View getInfoWindow(Marker marker) {
        Log.e(TAG, "getInfoWindow");
        View infoWindow = getLayoutInflater().inflate(
                R.layout.info_window, null);
        render(marker, infoWindow);
        return infoWindow;
    }
*/

    /* */

    @Override
    public View getInfoWindow(Marker marker) {
        return null;
    }

    /**
     * 自定义infowinfow窗口
     *//*
    public void render(Marker marker, View view) {
        TextView tv_time = (TextView) view.findViewById(R.id.tv_time);
        TextView tv_time_info = (TextView) view.findViewById(R.id.tv_time_info);
        TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
        tv_time.setText(time[0]);
        tv_time_info.setText(time[1]);
        tv_distance.setText(distance);
    }
*/
    @Override
    public View getInfoContents(Marker marker) {
        Log.e(TAG, "getInfoContents");
        return null;
    }


    @Override
    public void onLocationGet(PositionEntity entity) {
        // todo 这里在网络定位时可以减少一个逆地理编码
        Log.e("onLocationGet", "onLocationGet" + entity.address);
        RouteTask.getInstance(getApplicationContext()).setStartPoint(entity);
        mStartPosition = new LatLng(entity.latitue, entity.longitude);
        if (mIsFirstShow) {
            CameraUpdate cameraUpate = CameraUpdateFactory.newLatLngZoom(
                    mStartPosition, 17);
            aMap.animateCamera(cameraUpate);
            mIsFirstShow = false;
        }
        mInitialMark.setPosition(mStartPosition);
        initLocation = mStartPosition;
        Log.e("onLocationGet", "onLocationGet" + mStartPosition);

    }

    @Override
    public void onRegecodeGet(PositionEntity entity) {

    }

    private void playMusic() {
        if (openLockBean == null) {
            return;
        }
        if (CommonUtils.isEmpty(openLockBean.getSpeech())) {
            return;
        }
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(this, Uri.parse(openLockBean.getSpeech()));
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setLooping(false);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });

    }

    private void playMusic(String song) {

        if (CommonUtils.isEmpty(song)) {
            return;
        }
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        mediaPlayer.reset();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(this, Uri.parse(song));
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.setLooping(false);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                mediaPlayer.start();
            }
        });

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerAction(Message messageEvent) {
        switch (messageEvent.what) {
            case EventBusAction.PUSH_ACTION:
                NoticeBean bean = (NoticeBean) messageEvent.obj;
                switch (bean.getType()) {
                    //开锁成功
                    case NoticeBean.LOCK_OPEN:
                        viewDelegate.toast(getString(R.string.open_success));
                        openOrderBean = new OpenOrderBean(System.currentTimeMillis(), "");
                        showRidingState();
                        if (bean.getLocktype().equals(NoticeBean.LOCK_BLUE)) {
                            if (isOpen) {
                                return;
                            }
                            isOpen = true;

                            UserModel.blueOpenNotice(new ProgramSubscriber<HttpResult<List<String>>>() {
                                @Override
                                public void onNext(HttpResult<List<String>> listHttpResult) {
                                    playMusic(listHttpResult.getData().get(0));


                                }
                            }, AppUtils.getLockNumber(), App.getApp().amapLocation.getLongitude() + "", "" + App.getApp().amapLocation.getLatitude());
                        } else {
                            playMusic();
                        }

                        break;
                    //关锁成功
                    case NoticeBean.LOCK_CLOSE:
                        closeBlue();
                        viewDelegate.toast(getString(R.string.close_success));
                        if (timer != null) {
                            timer.cancel();
                            timer = null;
                        }

                        UserModel.closeLock(new ProgramSubscriber<HttpResult<ExpensesRecordBean>>() {
                            @Override
                            public void onNext(HttpResult<ExpensesRecordBean> expensesRecordBeanHttpResult) {
                                ExpensesRecordBean expensesRecordBean = expensesRecordBeanHttpResult.getData();
                               /*Bundle bundle = new Bundle();
                                bundle.putSerializable("expensesRecordBean", expensesRecordBeanHttpResult.getData());
                                readyGo(MyTripActivity.class, bundle);*/
                                viewDelegate.getRlRideEnd().setVisibility(View.VISIBLE);
                                viewDelegate.getRlRiding().setVisibility(View.GONE);
                                viewDelegate.getTvSpand().setText("¥" + expensesRecordBean.getExpensesAmount());
                                viewDelegate.getTvOverTime().setText(getString(R.string.end_time) + CommonUtils.formatLong(expensesRecordBean.getEndTime()));
                                viewDelegate.getTvBikeNumber().setText(getString(R.string.riding_bike_number) + expensesRecordBean.getLockNumber());
                                viewDelegate.get(R.id.iv_main_scan_open).setVisibility(View.VISIBLE);

                            }
                        }, bean.getData(), App.getApp().amapLocation.getLongitude() + "", "" + App.getApp().amapLocation.getLatitude());
                        break;
                }
                break;

            //展示更新
            case EventBusAction.UPDATE_VERSION:
                checkVersion();
                break;
            //更新apk下载进度
            case EventBusAction.DOWN_APK_PROGRESS:
                int progress = messageEvent.arg1;
                showLoadingDialog(progress);
                break;
            case EventBusAction.UPDATE_RIDING_TIME:
                long startTime = System.currentTimeMillis();
                if (openOrderBean != null) {
                    startTime = openOrderBean.getBeginTime();
                }
                long interval = System.currentTimeMillis() - startTime;
                viewDelegate.getTvRidingTime().setText(CommonUtils.secToTime((int) (interval / 1000)));
                break;

            case EventBusAction.OPEN_LOCK_BLUE_ERROE:
                viewDelegate.toast("开锁失败");
                closeBlue();
                break;
            case EventBusAction.LOCK_BLUE_CLOSE_SECCESS:
                if (lockBean == null) {
                    return;
                }
                if (CommonUtils.isEmpty(lockBean.getImei())) {
                    return;
                }
                UserModel.notice(new ProgramSubscriber<HttpResult<String>>() {
                    @Override
                    public void onNext(HttpResult<String> stringHttpResult) {

                    }
                }, lockBean.getImei());
                closeBlue();


                break;

        }
    }

    @Override
    public void onBackPressed() {
        finish();
        AppManager.getAppManager().finishAllActivity();
    }


    /**
     * @param currentProgress
     * protected Dialog loadingDialog;
     */
    View loadingView;

    public void showLoadingDialog(int currentProgress) {

        //使用父类的loadingDialog保证下载成功会dimiss掉dialog
        if (loadingDialog == null) {
            loadingView = LayoutInflater.from(this).inflate(R.layout.custom_download_layout, null);
            loadingDialog = new AlertDialog.Builder(this).setTitle("").setView(loadingView).create();
            loadingDialog.setCancelable(false);
            loadingDialog.setCanceledOnTouchOutside(false);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
        }
        ProgressBar pb = loadingView.findViewById(R.id.pb);
        TextView tvProgress = loadingView.findViewById(R.id.tv_progress);
        tvProgress.setText(String.format(getString(R.string.versionchecklib_progress), currentProgress));
        pb.setProgress(currentProgress);
        if (currentProgress > 99) {
            loadingDialog.dismiss();
            return;
        }
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }


    @Override
    public void onDismiss(DialogInterface dialog) {

    }

    protected boolean checkLocationPermission() {
        return EasyPermissions.hasPermissions(this, locPermissions);
    }

    protected void reqLocationPermission() {
        EasyPermissions.requestPermissions(this, "Android 6.0以上扫描蓝牙需要该权限",
                Permission.LOCATION, locPermissions);
    }

    /**
     * 扫描可用蓝牙
     */
    private void scanBt() {
        //对于6.0以上的申请地理位置动态权限
        if (!checkLocationPermission()) {
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
            builder.setTitle("请求权限")
                    .setMessage("Android 6.0 以上的系统版本，扫描蓝牙需要地理位置权限。请允许。")
                    .setNeutralButton("取消", null)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //调用请求权限
                            reqLocationPermission();
                        }
                    }).show();
            return;
        }
        //如果是7.0以上,判断定位服务设置（GPS,NET）是否开启
      /*  if (APIVersionUtil.isAtLeast(Build.VERSION_CODES.N) &&
                LocationSettingUtil.isLocServiceOpen(this)) {
            Toast.makeText(this, "您的Android版本在7.0以上，扫描需要打开位置信息。",
                    Toast.LENGTH_LONG).show();
            //去开启
            LocationSettingUtil.goLocServiceSetting(this);
            return;
        }*/

        //扫描
        SearchRequest searchRequest =
                new SearchRequest.Builder()
                        //先扫BLE设备3次每次5秒
                        .searchBluetoothLeDevice(5000, 3)
                        //再扫经典蓝牙5s
                        .searchBluetoothClassicDevice(5000)
                        //再扫BLE设备3s
                        .searchBluetoothLeDevice(3000)
                        .build();

        mBtClient.search(searchRequest, new SearchResponse() {
            @Override
            public void onSearchStarted() {

            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (!mBtItems.contains(device.device)) {
                    mBtItems.add(device.device);
                }

                Beacon beacon = new Beacon(device.scanRecord);
                BluetoothLog.v(String.format("beacon for %s\n%s", device.getAddress(), beacon.toString()));
            }

            @Override
            public void onSearchStopped() {

            }

            @Override
            public void onSearchCanceled() {

            }
        });


    }

    private void initBT() {
        btStateListener = new BluetoothStateListener() {
            @Override
            public void onBluetoothStateChanged(boolean openOrClosed) {
                if (isScanning && openOrClosed) {
                    scanBt();//
                }
            }
        };

        mBtClient.registerBluetoothStateListener(btStateListener);
    }

    private void connectAndOpen(LockBean lockBean) {
        //  ControlBlueUtils controlBlueUtils = new ControlBlueUtils(mBtClient, "D0:4C:D0:03:6B:70");
        ControlBlueUtils controlBlueUtils = new ControlBlueUtils(mBtClient, lockBean.getMac(), lockBean.getBluetoothCipher());
        blueMac = lockBean.getMac();
        controlBlueUtils.connect();
        readyGo(OpenLockActivity.class);


    }

    private void closeBlue() {
        if (mBtClient != null && !CommonUtils.isEmpty(blueMac)) {
            mBtClient.disconnect(blueMac);
        }
    }
}
